"use strict";

/**
 * 查找满足条件的节点
 *
 * @since 0.0.5
 * @category 树算法
 * @param {array} treeList 树形结构集合.
 * @param {any|function} param 唯一key或者校验函数.
 * @param {object} config 配置参数.
 * @param {boolean} config.props 属性配置
 * @param {string} config.props.prop 数据的唯一主键key, 默认: id.
 * @param {string} config.props.childrenProp 数据的子主键key, 默认: children.
 *
 * @returns { object } 查找到的节点
 *
 * @example
 *
 * z.treeFindNode([ { id: 1, children: [ { id: 3, parentId: 1 } ] }, { id: 2 } ], 3)
 * // => { id: 3, parentId: 1 }
 *
 * z.treeFindNode([ { code: 1, pCode: '', list: [ { code: 3, pCode: 1 } ] }, { code: 2, pCode: '' } ], node => node.code === 3, { props: { prop: 'code', childrenProp: 'list' }})
 * // => { code: 3, pCode: 1 }
 *
 */
function treeFindNode(treeList, param) {
  var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
      _ref$props = _ref.props;

  _ref$props = _ref$props === void 0 ? {} : _ref$props;
  var _ref$props$prop = _ref$props.prop,
      prop = _ref$props$prop === void 0 ? 'id' : _ref$props$prop,
      _ref$props$childrenPr = _ref$props.childrenProp,
      childrenProp = _ref$props$childrenPr === void 0 ? 'children' : _ref$props$childrenPr;
  var callback = param;

  if (typeof callback !== 'function') {
    callback = function callback(node) {
      return node[prop] === param;
    };
  }

  var func = function func(array) {
    for (var i = 0; i < array.length; i++) {
      var item = array[i];
      var rt = callback(item);
      if (rt) return item;

      if (item[childrenProp]) {
        var _rt = func(item[childrenProp]);

        if (_rt) return _rt;
      }
    }
  };

  return func(treeList);
}

module.exports = treeFindNode;